#include "logger.h"

Logger::Logger() : syncSem(0)
{
    runPath = QDir::currentPath() + "/log";
    init(runPath);
}

QString Logger::init(QString path)
{
    return createDir(path);
}

void Logger::write(int msgType, const QString &msg)
{
    mutex.lock();

    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString current_date;
    switch(msgType) {
    case MSG_DEFAULT:
        current_date = QString("[程  序] %1").arg(current_date_time);
        break;
    default:
        current_date = QString("[程  序] %1").arg(current_date_time);;
        break;
    }
    LogMessage logMessage;
    QString message = QString("%1 %2").arg(current_date).arg(msg);
    logMessage.message = message;
    msgList.push_back(logMessage);

    mutex.unlock();
    syncSem.release();//释放
}

void Logger::run()
{
    while(running) {
        syncSem.acquire();//堵塞

        mutex.lock();

        if(msgList.isEmpty()) {
            continue;
        }
        LogMessage log = msgList.front();
        msgList.pop_front();

#ifdef DEBUG
        qDebug() << log.message;
#else
        QString date  = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        QString logName = QString("%1/%2.txt").arg(runPath).arg(date);
        QFile file(logName);
        file.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream text_stream(&file);
        text_stream << log.message << "\r\n";
        file.flush();
        file.close();
#endif
        mutex.unlock();
    }
}

void Logger::setRunning(bool running)
{
    this->running = running;
}

QString Logger::createDir(QString path)
{
    QDir dir(path);
    if ( dir.exists(path)){
        return path;
    }
    QString parentDir = createDir(path.mid(0, path.lastIndexOf('/')));
    QString dirname = path.mid(path.lastIndexOf('/') + 1);
    QDir parentPath(parentDir);
    if ( !dirname.isEmpty() )
        parentPath.mkpath(dirname);

    return parentDir + "/" + dirname;
}
